import { useEffect, useState } from 'react';
import { IS_BROWSER } from '../utils/detect';

function usePageVisibility(): 'visible' | 'hidden' {
	const [visibility, setVisibility] =
		useState<'visible' | 'hidden'>('visible');

	useEffect(() => {
		if (!IS_BROWSER) {
			return;
		}

		const onChange = () => {
			setVisibility(document.visibilityState);
		};

		document.addEventListener('visibilitychange', onChange);

		return () => {
			document.removeEventListener('visibilitychange', onChange);
		};
	}, []);

	return visibility;
}

export default usePageVisibility;
